package info.empathymobile.batterymonitorapp;

import info.empathymobile.monitor.EmpathyMonitorService;
import info.empathymobile.monitor.business.DatabaseHelper;
import info.empathymobile.monitor.business.OrmLiteBase;

import java.util.regex.Pattern;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.text.util.Linkify;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;

public class MainActivity extends OrmLiteBaseActivity<DatabaseHelper> implements OrmLiteBase<DatabaseHelper> {
	
	public final static String EMPATHY_SURVEY_SHARED_PREFERENCES = "EmpathySurvey";
	private SharedPreferences sharedPref;
	private SharedPreferences.Editor sharedPrefEditor;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		this.sharedPref = getSharedPreferences(EMPATHY_SURVEY_SHARED_PREFERENCES, Context.MODE_MULTI_PROCESS);
		sharedPrefEditor = this.sharedPref.edit();
		
		//Serviço do EmpathyMonitor
		Intent empathyMonitorServiceIntent = new Intent(this, EmpathyMonitorService.class);
		startService(empathyMonitorServiceIntent);
		
		//Serviço de sincronização dos dados de monitoração
		Intent serverSyncServiceIntent = new Intent(this, ServerSyncService.class);
		startService(serverSyncServiceIntent);

		if (!haveTheUserSawVersionChanges()) {
			onShowVersionChangesDialog();
			rememberThis_theUserSawVersionChanges();
		}
		
		TextView linkToMyDataOnServerTxt = (TextView)findViewById(R.id.link_to_my_data_on_server);
		Pattern pattern = Pattern.compile("");
		Linkify.addLinks(linkToMyDataOnServerTxt,pattern, "http://www.empathymobile.info/server/show_user_entries?user_uuid="+new ServerSyncBO().getUserUUID(this));
	}
	
	protected void onShowResearchParticipationTermsDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setMessage(R.string.acceptance_dlg_text)
		       .setTitle(R.string.acceptance_dlg_title);
		builder.setNegativeButton(R.string.dlg_close, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.dismiss();
			}
		});
		
		AlertDialog dialog = builder.create();
		dialog.show();
		
		TextView messageView = (TextView)dialog.findViewById(android.R.id.message);
		messageView.setGravity(Gravity.CENTER_HORIZONTAL);
		Linkify.addLinks(messageView, Linkify.ALL);
	}
	
	protected void onShowVersionChangesDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setMessage(R.string.version_changes_dlg_text)
		       .setTitle(R.string.version_changes_dlg_title);
		builder.setNegativeButton(R.string.dlg_close, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.dismiss();
			}
		});
		
		AlertDialog dialog = builder.create();
		dialog.show();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		if(item.getItemId() == R.id.action_see_research_terms){
			onShowResearchParticipationTermsDialog();
		}
		else if(item.getItemId() == R.id.action_empathy_page_link){
			openEmpathyMobileWebPage();
		} 
		return super.onMenuItemSelected(featureId, item);
	}

	private void openEmpathyMobileWebPage() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setData(Uri.parse("http://www.empathymobile.info"));
		startActivity(intent);
	}
	
	private boolean haveTheUserSawVersionChanges(){
		try {
			String versionName = this.getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
			String sawVersionChangesKey = "saw_version_" + versionName + "_changes";
			return this.sharedPref.getBoolean(sawVersionChangesKey,false);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	private void rememberThis_theUserSawVersionChanges(){
		try {
			String versionName = this.getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
			String sawVersionChangesKey = "saw_version_" + versionName + "_changes";
			this.sharedPrefEditor.putBoolean(sawVersionChangesKey, true);
			this.sharedPrefEditor.commit();
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
	}
}
